package com.rpcfx.api;

import com.rpcfx.api.spi.ProtobufSerialization;
import com.rpcfx.transports.NettyHttpClient;

import java.lang.reflect.Method;

/**
 * @ProjectName: learning
 * @Package: com.rpcfx.client
 * @ClassName: Invoker
 * @Description:
 * @Date: 2021/11/11 11:27 下午
 * @Version: 1.0
 */
public class Invoker {

    private Class<?> interfaceClass;

    private String url;


    public Invoker(Class<?> interfaceClass, String url) {
        this.interfaceClass = interfaceClass;
        this.url = url + "/" + interfaceClass.getName();
    }

    //url : http://127.0.0.1:8888/com.test.api.UserService/method?

    public RpcfxResponse invoke(Method method, Object[] args) {
        System.out.println("调用了:" + method.getName() + ",参数为:" + args);

        NettyHttpClient httpClient = new NettyHttpClient();
        boolean oneWay = isOneWay(method);
        byte[] resultBytes = (byte[]) httpClient.post(url, method.getName(), args, oneWay);

        Serialization serialization = new ProtobufSerialization();
        Object obj = serialization.deserialize(resultBytes);

        RpcfxResponse result = new RpcfxResponse();
        result.setSuccess(true);
        if (obj instanceof RpcfxException) {
            result.setSuccess(false);
            result.setRpcfxException((RpcfxException) obj);
        }
        result.setData(obj);
        return result;
    }

    private boolean isOneWay(Method method) {
        Class<?> returnType = method.getReturnType();
        return returnType == void.class || returnType == Void.class;
    }

}
